﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using JetBrains.Annotations;
using K9Nano.Application;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.IdentityServerCore.Extensions;
using K9Nano.IdentityServerCore.Roles.Dto;
using K9Nano.Runtime;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using AppRole = K9Nano.Authentication.Role;

namespace K9Nano.IdentityServerCore.Roles
{
    public class RoleCurdAppService : ApplicationService,
        ICurdApplicationService<AppRole, RoleCreateDto, RoleCreateDto, RoleItemDto,
        RolePagedInputDto, long>, IScopedDependency
    {
        private readonly RoleManager<AppRole> _roleManager;

        public RoleCurdAppService(IUnitOfWork uow, IMapper mapper, ISessionContext sessionContext, ILoggerFactory loggerFactory,
            [NotNull] RoleManager<AppRole> roleManager) : base(uow, mapper, sessionContext, loggerFactory)
        {
            _roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
        }

        public async Task<RoleItemDto> CreateAsync(RoleCreateDto dto, CancellationToken cancellation = default)
        {
            var role = Mapper.Map<AppRole>(dto);
            var result = await _roleManager.CreateAsync(role);
            if (result.Succeeded)
            {
                return Mapper.Map<RoleItemDto>(role);
            }

            throw result.ToException();
        }

        public async Task<RoleItemDto> UpdateAsync(RoleCreateDto dto, CancellationToken cancellation = default)
        {
            var role = Mapper.Map<AppRole>(dto);
            var result = await _roleManager.UpdateAsync(role);
            if (result.Succeeded)
            {
                return Mapper.Map<RoleItemDto>(role);
            }

            throw result.ToException();
        }

        public async Task<PagedResultDto<RoleItemDto>> ListAsync(RolePagedInputDto input, CancellationToken cancellation = default)
        {
            var repository = Uow.Repository<AppRole, long>();
            var count = await repository.CountAsync(input.Predicate(), cancellation);
            if (count <= 0) return new PagedResultDto<RoleItemDto>();
            var result = await repository.GetPagedListAsync(input.Predicate(), input.OrderBy(), input.Skip(), input.PageSize, cancellation);
            var list = Mapper.Map<List<RoleItemDto>>(result);
            return new PagedResultDto<RoleItemDto>(count, list);
        }

        public async Task DeleteAsync(long id, CancellationToken cancellation = default)
        {
            var role = await Uow.Repository<AppRole, long>().GetAsync(id, cancellation);
            if (role != null)
            {
                await _roleManager.DeleteAsync(role);
            }
        }

        public async Task<IReadOnlyList<RoleItemDto>> ListAsync(string[] roles, CancellationToken cancellation = default)
        {
            var repository = Uow.Repository<AppRole, long>();

            var result = await repository.GetAllListAsync(r => roles.Contains(r.Name), cancellation);
            var list = Mapper.Map<List<RoleItemDto>>(result);
            return list;
        }
    }
}